package hapi.store;

import hapi.ontology.HL7Ontology;
import jade.content.lang.sl.SLCodec;
import jade.core.Agent;
import jade.core.behaviours.Behaviour;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.Property;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.lang.acl.ACLMessage;

import java.util.Random;

import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.model.Message;
import ca.uhn.hl7v2.parser.EncodingNotSupportedException;
import ca.uhn.hl7v2.parser.GenericParser;
import ca.uhn.hl7v2.parser.Parser;
import ca.uhn.hl7v2.util.Terser;

public class AdmitAgent extends Agent{

protected void setup() {
		
		//System.out.println("[Store Agent: Setup init...]");
		getContentManager().registerLanguage(new SLCodec());
		getContentManager().registerOntology(HL7Ontology.getInstance());

		// DBconnection con = new DBconnection();
		DBconnection.connect();

		try {
			// REGISTO DO AGENTE NAS PAGINAS AMARELAS
			DFAgentDescription dfd = new DFAgentDescription();
			dfd.setName(getAID());
			ServiceDescription sd = new ServiceDescription();
			sd.setType(HL7Ontology.DATABASE_STORAGE);
			sd.setName(getLocalName());
			Property p = new Property();
			p.setName("Type");
			p.setValue(new String("A01"));
			sd.addProperties(p);
			dfd.addServices(sd);
			DFService.register(this, dfd);
		} catch (FIPAException fe) {
			fe.printStackTrace();
		}

		addBehaviour(new Behaviour(this) {		
			public void action() {
				//System.out.println("[Store Agent]:");
				ACLMessage msg = receive();
				if (msg != null){
					//System.out.println("Recebe Msn");
					admit_mensagem(msg);
				}else{
					block();
				}
			}

			@Override
			public boolean done() {
				
				return false;
			}
		});

	}

	public void admit_mensagem(ACLMessage msg) {

		if (msg != null) {
			String ms = msg.getContent();
			//System.out.println(ms);
			try {
				Parser p = new GenericParser();
				Message hapiMsg = p.parse(ms);
				Terser terser = new Terser(hapiMsg);
				String id = terser.get("/.PID-3-1");
				a_mensagem(id);
			} catch (EncodingNotSupportedException e) {
				e.printStackTrace();
			} catch (HL7Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void a_mensagem(String id) {
		Random r = new Random();
		int num = r.nextInt();
		String sql_code = "update patient set state = 1 where pid="+id;
		//System.out.println(sql_code);
		DBconnection.execute_query(sql_code);
		System.out.println("Admit depois: "+System.currentTimeMillis());
	}
	
}
